<template>
  <div class="form-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <h2>发布招聘信息</h2>
          <p>填写详细的职位信息，吸引优秀人才</p>
        </div>
      </template>

      <el-form ref="formRef" :model="jobForm" :rules="formRules" label-width="120px" class="job-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>

          <el-form-item label="职位标题" prop="title">
            <el-input v-model="jobForm.title" placeholder="请输入职位标题，如：招聘服务员" maxlength="50" show-word-limit />
          </el-form-item>

          <el-form-item label="公司名称" prop="company">
            <el-input v-model="jobForm.company" placeholder="请输入公司名称" maxlength="50" />
          </el-form-item>

          <el-form-item label="工作类型" prop="jobType">
            <el-select v-model="jobForm.jobType" placeholder="请选择工作类型" style="width: 100%">
              <el-option label="全职" value="fulltime" />
              <el-option label="兼职" value="parttime" />
              <el-option label="实习" value="internship" />
            </el-select>
          </el-form-item>

          <el-form-item label="工作地点" prop="location">
            <el-input v-model="jobForm.location" placeholder="请输入工作地点，如：凯通路42号" />
          </el-form-item>

          <el-form-item label="薪资范围" prop="salaryRange">
            <el-input v-model="jobForm.salaryRange" placeholder="请输入薪资范围，如：3000-5000" />
          </el-form-item>
        </div>

        <!-- 职位要求 -->
        <div class="form-section">
          <h3 class="section-title">职位要求</h3>

          <el-form-item label="学历要求" prop="education">
            <el-select v-model="jobForm.education" placeholder="请选择学历要求" style="width: 100%">
              <el-option label="不限" value="不限" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>

          <el-form-item label="工作经验" prop="experience">
            <el-select v-model="jobForm.experience" placeholder="请选择工作经验要求" style="width: 100%">
              <el-option label="不限" value="不限" />
              <el-option label="应届生" value="应届生" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-6年" value="3-6年" />
              <el-option label="6-10年" value="6-10年" />
              <el-option label="10年以上" value="10年以上" />
            </el-select>
          </el-form-item>

          <el-form-item label="公司福利" prop="tags">
            <div class="tags-input">
              <el-tag v-for="tag in jobForm.tagsJson" :key="tag" closable @close="removeTag(tag)" class="tag-item">
                {{ tag }}
              </el-tag>
              <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" class="tag-input" />
              <el-button v-else size="small" @click="showInput">+ 添加福利</el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 职位描述 -->
        <div class="form-section">
          <h3 class="section-title">职位描述</h3>

          <el-form-item label="工作职责" prop="responsibilities">
            <el-input v-model="jobForm.responsibilities" type="textarea" :rows="4" placeholder="如：负责卫生打扫，收拾碗筷，服务顾客" maxlength="1000" show-word-limit />
          </el-form-item>

          <el-form-item label="任职要求" prop="requirements">
            <el-input v-model="jobForm.requirements" type="textarea" :rows="4" placeholder="如：要求会骑车，会电脑，会写自己名字" maxlength="1000" show-word-limit />
          </el-form-item>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <h3 class="section-title">联系信息</h3>

          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="jobForm.contactPerson" placeholder="请输入联系人姓名" />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="jobForm.phone" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="公司头像" v-if="false">
            <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="handleAvatarUpload">
              <img v-if="jobForm.face" :src="jobForm.face" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <!-- 提交按钮 -->
      <div class="submit-section">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> 发布职位 </el-button>
        <el-button size="large" @click="resetForm">重置</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/apis/zhaopin'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'

import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const user = computed(() => userStore.userInfo)
// console.log(userStore.userInfo)
// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()

// 表单数据
const jobForm = reactive({
  title: '',
  company: '',
  jobType: '全职',
  tagsJson: ['包吃住'],
  location: '',
  salaryRange: '',
  responsibilities: '',
  requirements: '',
  contactPerson: '',
  phone: '',
  education: '',
  experience: '',
  face: user.value.avatar || ''
})

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')

// 状态管理
const submitting = ref(false)

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入职位标题', trigger: 'blur' },
    { min: 2, max: 50, message: '职位标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  jobType: [{ required: true, message: '请选择工作类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  salaryRange: [{ required: true, message: '请输入薪资范围', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入任职要求', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  education: [{ required: true, message: '请选择学历要求', trigger: 'change' }],
  experience: [{ required: true, message: '请选择工作经验要求', trigger: 'change' }]
}

// 添加标签
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !jobForm.tagsJson.includes(inputValue.value)) {
    jobForm.tagsJson.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const removeTag = (tag: string) => {
  const index = jobForm.tagsJson.indexOf(tag)
  if (index > -1) {
    jobForm.tagsJson.splice(index, 1)
  }
}

// 头像上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = (options: any) => {
  // 这里模拟上传，实际项目中需要调用真实的上传接口
  const reader = new FileReader()
  reader.onload = (e) => {
    jobForm.face = e.target?.result as string
  }
  reader.readAsDataURL(options.file)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...jobForm,
      tagsJson: ''
    }
    submitData.tagsJson = JSON.stringify(jobForm.tagsJson)
    // API调用
    http
      .create(submitData)
      .then((response) => {
        let { code, message } = response.data
        if (code != 200) {
          ElMessage.error(message)
          return
        }
        ElMessage.success('职位发布成功！')
      })
      .catch(() => {
        ElMessage.error('职位发布失败，请稍后重试')
      })
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    jobForm.tagsJson = []
    jobForm.face = ''
    ElMessage.success('表单已重置')
  })
}
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .job-posting-container {
    padding: 16px;
  }

  .job-form :deep(.el-form-item__label) {
    width: 100px !important;
  }

  .tags-input {
    flex-direction: column;
    align-items: flex-start;
  }

  .submit-section .el-button {
    margin: 4px;
    min-width: 100px;
  }
}
</style>
